<?php
/**
 * Created by PhpStorm.
 * User: lzy
 * Date: 2019/2/22
 * Time: 21:23
 */
namespace App\Ordersys\Controllers\Admin;

use App\Admin\Models\AuthGroupAccessModel;
use App\Admin\Models\MemberModel;
use App\Base\Controllers\Controller;
use App\Ordersys\Contracts\OrderApplyInterface;
use App\Ordersys\Contracts\OrdersysOrderInterface;
use App\Ordersys\Contracts\OrdersysShippingInterface;
use App\Ordersys\Models\OrdersysOrderExpressModel;
use App\Ordersys\Models\OrdersysOrderModel;
use App\Ordersys\Models\OrdersysShippingModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class ApplyController  extends Controller
{


    /**
     * 订单接口
     * @return OrdersysOrderInterface
     */
    public function getOrdersysOrderInterface(){
        return app()->make(OrdersysOrderInterface::class);
    }


    /**
     * 订单管理接口
     * @return OrderApplyInterface
     */
    public function getOrderApplyInterface(){
        return app()->make(OrderApplyInterface::class);
    }


    /**
     * 总订单列表
     */
    public function index(Request $request){
        if ($request->getMethod() == 'POST') {

            $where=function($query) use ($request){
                $data = $request->all();
                if (!empty($data["start_date"])) {
                    $query->where("add_time", ">", strtotime($data["start_date"]));
                }
                if (!empty($data["end_date"])) {
                    $query->where("add_time", "<", strtotime($data["end_date"] . " 23:59:59"));
                }
                if (!empty($data['wx_no'])) {
                    $query->where("wx_no", "like", '%' . $data['wx_no'] . '%');
                }
                if (!empty($data['sale_name'])) {
                    $query->where("sale_name", "like", '%' . $data['sale_name'] . '%');
                }
                if(!empty($data['add_fen_month'])){
                    if($data['add_fen_month']!=''){
                        $query->where("add_fen_month",$data['add_fen_month']);
                    }
                }
                if(!empty($data['pt_name'])) {
                    if ($data['pt_name'] != '') {
                        $query->where("pt_name", $data['pt_name']);
                    }
                }
                if(!empty($data['order_type'])){
                    $query->where("order_type",$data['order_type']);
                }
                 if(!empty($data['add_fen_type'])){
                     $query->where("add_fen_type",$data['add_fen_type']);
                 }
                if(!empty($data['apply_status'])) {
                    if ($data['apply_status'] != '') {
                        $query->where("apply_status", $data['apply_status']);
                    }
                }
            };
            return $this->getOrdersysOrderInterface()->getList($where);
        }
        return view("ordersys.apply.index");
    }

    /**
     * 分产品订单列表
     * @param Request $request
     */
    public function goodsIndex(Request $request){
        if ($request->getMethod() == 'POST') {
            $where = function ($query) use ($request) {
                $data = $request->all();
                if (!empty($data["start_date"])) {
                    $query->where("add_time", ">", strtotime($data["start_date"]));
                }
                if (!empty($data["end_date"])) {
                    $query->where("add_time", "<", strtotime($data["end_date"] . " 23:59:59"));
                }
                if (!empty($data['receiver'])) {
                    $query->where("receiver", "like", '%' . $data['receiver'] . '%');
                }
                if (!empty($data['receiver_tel'])) {
                    $query->where("receiver_tel", "like", '%' . $data['receiver_tel'] . '%');
                }
                if(!empty($data['shipping_code'])){
                    $query->where("shipping_code","like",'%'.$data['shipping_code'].'%');
                }
                if(!empty($data['apply_status'])){
                    $query->where("apply_status",$data['apply_status']);
                }

                if(!empty($data["wx_no"])){
                    $query->where("wx_no", "like", '%' . $data["wx_no"] . '%');
                }
//                if($data['shipping_status']==0){
//                    $query->where("ordersys_order_express.shipping_status",0);
//                }

                if(!empty($data['sale_id'])){
                    $query->where("sale_id",$data['sale_id']);
                }
                if(isset($data['shipping_status'])){
                    $query->where("ordersys_order_express.shipping_status",$data['shipping_status']);
                }


                if(isset($data['express_type'])){
                    $query->where("express_type",$data['express_type']);
                }
//                if(!empty($data['shipping_status'])){
//                    $query->where("ordersys_order_express.shipping_status",$data['shipping_status']);
//                }
                //$query->where("uid", UID);
                $query->where("order_type", 1);
            };

            return $this->getOrdersysOrderInterface()->getOrderListExpressList($where);
        }
        if (IS_ROOT) {
            $where = array();
            $where[$this->getAuthGroupAccessModel()->table.".group_id"] = 1;
            $memberList= $this->getAuthGroupAccessModel()->newQuery()
                ->select([$this->getAuthGroupAccessModel()->table.".uid",$this->getMemberModel()->table.".nickname"])
                ->leftJoin($this->getMemberModel()->table, $this->getAuthGroupAccessModel()->table . '.uid', '=', $this->getMemberModel()->table . '.uid')->where($where)->get();
        } else {
            $memberList =$this->getMemberModel()->select(["uid","nickname"])->where(array("uid" => UID))->get();
        }
        $where=function($query){
            $query->where("status",1);
        };
        $shipping_list=$this->getOrdersysShippingInterface()->getAllList($where);
        return view("ordersys.apply.goods")->with("memberList",$memberList)->with("mid",UID)->with("shippingList",$shipping_list);
    }
    /**
     * @return AuthGroupAccessModel
     */
    public function getAuthGroupAccessModel(){
        return app()->make(AuthGroupAccessModel::class);
    }

    /**
     * 用户
     * @return MemberModel
     */
    public function getMemberModel(){
        return app()->make(MemberModel::class);
    }
    /**
     * 分充值订单列表
     */
    public function rechargeIndex(Request $request){
        if ($request->getMethod() == 'POST') {
            $where = function ($query) use ($request) {
                $data = $request->all();
                if (!empty($data["start_date"])) {
                    $query->where("add_time", ">", strtotime($data["start_date"]));
                }
                if (!empty($data["end_date"])) {
                    $query->where("add_time", "<", strtotime($data["end_date"] . " 23:59:59"));
                }
                $pay_uid = $request->input("pay_uid");
                if (!empty($pay_uid)) {
                    $query->where("pay_uid", $pay_uid);
                }
                //$query->where("uid", UID);
                $query->where("order_type", 2);
            };
            return $this->getOrdersysOrderInterface()->getList($where);
        }
        return view("ordersys.apply.recharge");
    }

    /**
     * 订单模块
     * @return OrdersysOrderModel
     */
    public function getOrdersysOrderModel(){
        return app()->make(OrdersysOrderModel::class);
    }

    /**
     * 快递
     * @return OrdersysShippingInterface
     */
    public function getOrdersysShippingInterface(){
        return app()->make(OrdersysShippingInterface::class);
    }
    /**
     * 详细
     * @param Request $request
     */
    public function detail(Request $request){
        $id=$request->input("id");
        $orderInfo=$this->getOrdersysOrderInterface()->getInfo($id);
        if($orderInfo->order_type==1){
            $where=function($query) use ($id){
                 $query->where($this->getOrdersysOrderModel()->table.".id",$id);
            };
            $info=$this->getOrdersysOrderInterface()->getOrderListExpressInfo($where);

            return view("ordersys.apply.goods_detail")->with("info",$info);
        }else{
            return view("ordersys.apply.recharge_detail")->with("info",$orderInfo);
        }
    }


    /***
     * 审请通过
     * @param Request $request
     */
    public function applyTrue(Request $request){

        if ($request->getMethod() == 'POST') {
           return $this->getOrderApplyInterface()->applyTrue($request->all());
        }
    }


    /**
     * 审请拒绝
     * @param Request $request
     */
    public function applyError(Request $request){
        if ($request->getMethod() == 'POST') {

            return $this->getOrderApplyInterface()->applyError($request->all());
        }
    }

    /**
     * 设置物流
     * @param Request $request
     */
    public function setShipping(Request $request){
        $id=$request->input("id");
        if ($request->getMethod() == 'POST') {
             $this->getOrderApplyInterface()->changeShippingCode($request->all());
        }
        $where=function($query) use ($id){
            $query->where($this->getOrdersysOrderModel()->table.".id",$id);
        };
        $info=$this->getOrdersysOrderInterface()->getOrderListExpressInfo($where);

        $where=function($query){
            $query->where("status",1);
        };
        $shipping_list=$this->getOrdersysShippingInterface()->getAllList($where);
        return view("ordersys.apply.set_shipping")->with("shippingList",$shipping_list)->with("info",$info)->with("order_id",$id);
    }

    /**
     * @return OrdersysShippingModel
     */
    public function getOrdersysShippingModel(){
        return app()->make(OrdersysShippingModel::class);
    }

    /***
     * @return OrdersysOrderExpressModel
     */
    public function getOrdersysOrderExpressModel(){
        return app()->make(OrdersysOrderExpressModel::class);
    }
    /**
     * 查看物流
     * @param Request $request
     */
    public function showShipping(Request $request){

       // throw new \Exception("请先去申请才能开通");
        $id=$request->input("id");
        $info=$this->getOrdersysOrderInterface()->getInfo($id);
        $express_type=$this->getOrdersysOrderExpressModel()->newQuery()->where("order_id",$info->id)->value("express_type");
        $com=$this->getOrdersysShippingModel()->newQuery()->where("title",$express_type)->value("com"); //"shunfeng";            //
        $shipping_code =$info->shipping_code;  //"254104009238";
        $post_data = array();
        $post_data["customer"] = '94FB71D8C0AE4B48D975F226ACD97899';
        $key= 'Alexcnsh3459' ;
        $post_data["param"] = '{"com":"'.$com.'","num":"'.$shipping_code.'"}';
        $url='http://poll.kuaidi100.com/poll/query.do';
        $post_data["sign"] = md5($post_data["param"].$key.$post_data["customer"]);
        $post_data["sign"] = strtoupper($post_data["sign"]);
        $o="";
        foreach ($post_data as $k=>$v)
        {
            $o.= "$k=".urlencode($v)."&";		//默认UTF-8编码格式
        }
        $post_data=substr($o,0,-1);
        $result=$this->sendCurlPost($url,$post_data);
        $data = str_replace("\"",'"',$result );
        $data = json_decode($data,true);

        if(!empty($data['status'])){
            if($data['status']==200){
                return view("ordersys.apply.show_shipping")->with("arr",$data['data'])->with("shipping_code",$info->shipping_code)->with("express_type",$express_type)->with("info",$info);
            }else{
                echo "查无物流";
                exit;
            }
        }else{
            if($data['returnCode']==500){
                echo $data['message'];
                exit;
            }
        }
        echo "查无物流";
        exit;


    }

    public function sendCurlPost($url, $dataObj)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $dataObj);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        $ret = curl_exec($curl);
        if (false == $ret) {
            // curl_exec failed
            $result = "{ \"result\":" . -2 . ",\"errmsg\":\"" . curl_error($curl) . "\"}";
        } else {
            $rsp = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            if (200 != $rsp) {
                $result = "{ \"result\":" . -1 . ",\"errmsg\":\"" . $rsp
                    . " " . curl_error($curl) . "\"}";
            } else {
                $result = $ret;
            }
        }
        curl_close($curl);
        return $result;
    }

    /*
     * 返回$data array      快递数组查询失败返回false
     * @param $order        快递的单号
     * $data['ischeck'] ==1 已经签收
     * $data['data']        快递实时查询的状态 array
     */

    public function getorder($order) {

        $keywords = $this->expressname($order);
        if (!$keywords) {
            return false;
        } else {
           // $c=$this->getcontent("http://www.kuaidi100.com/query?type=huitongkuaidi&postid=51339042306112");

            $result = $this->getcontent("http://www.kuaidi100.com/query?type={$keywords}&postid={$order}");
            $data = json_decode($result, true);

            if($data['status']!=200){
                return false;
            }
            return $data;
        }
    }
    /*
       * 获取对应名称和对应传值的方法
       */

    private function expressname($order) {
        $name = json_decode($this->getcontent("http://www.kuaidi100.com/autonumber/auto?num={$order}"), true);
        $result = $name[0]['comCode'];
        if (empty($result)) {
            return false;
        } else {
            return $result;
        }
    }
    /*
    * 网页内容获取方法
    */

    private function getcontent($url) {
        if (function_exists("file_get_contents")) {
            $file_contents = file_get_contents($url);
        } else {
            $ch = curl_init();
            $timeout = 5;
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
            $file_contents = curl_exec($ch);
            curl_close($ch);
        }
        return $file_contents;
    }

    /**
     * 退款提交
     * @param Request $request
     */
    public function backMoney(Request $request){
        $id=$request->input("id");
        if ($request->getMethod() == 'POST') {
             return $this->getOrderApplyInterface()->backMoney($request->all());
        }

        $info=$this->getOrdersysOrderInterface()->getInfo($id);
        return view("ordersys.apply.back_money")->with("info",$info);
    }

    /**
     * 确认退款
     * @param Request $request
     */
    public function backApplyTrue(Request $request){
        if ($request->getMethod() == 'POST') {
            return $this->getOrderApplyInterface()->backApplyTrue($request->all());
        }
    }

    /**
     * 拒绝退款
     * @param Request $request
     */
    public function backApplyError(Request $request){
        if ($request->getMethod() == 'POST') {
            return $this->getOrderApplyInterface()->backApplyError($request->all());
        }
    }

    /**
     * 退款列表
     */
    public function backIndex(Request $request){

        if ($request->getMethod() == 'POST') {
            $where=function($query) use ($request){
                $query->where("refund_state","<>",0);
            };
            return $this->getOrdersysOrderInterface()->getList($where);
        }
        return view("ordersys.apply.back_index");
    }

    public function exportExcel(Request $request){

        $where = function ($query) use ($request) {
            $data = $request->all();
            if (!empty($data["start_date"])) {
                $query->where("add_time", ">", strtotime($data["start_date"]));
            }
            if (!empty($data["end_date"])) {
                $query->where("add_time", "<", strtotime($data["end_date"] . " 23:59:59"));
            }
            if (!empty($data['receiver'])) {
                $query->where("receiver", "like", '%' . $data['receiver'] . '%');
            }
            if (!empty($data['receiver_tel'])) {
                $query->where("receiver_tel", "like", '%' . $data['receiver_tel'] . '%');
            }
            if(!empty($data['shipping_code'])){
                $query->where("shipping_code","like",'%'.$data['shipping_code'].'%');
            }
            if(!empty($data['apply_status'])){
                $query->where("apply_status",$data['apply_status']);
            }
            if(!empty($data["wx_no"])){
                $query->where("wx_no", "like", '%' . $data["wx_no"] . '%');
            }
            if(isset($data['shipping_status'])){
                $query->where("ordersys_order_express.shipping_status",$data['shipping_status']);
            }
            if(isset($data['express_type'])){
                $query->where("express_type",$data['express_type']);
            }
            if(!empty($data['sale_id'])){
                $query->where("sale_id",$data['sale_id']);
            }
            //$query->where("uid", UID);
            $query->where("order_type", 1);
        };
        $allList=$this->getOrdersysOrderInterface()->getOrderListExpressListAll($where);

        $cellData=array();
        $cellData[0] = [
            "添加时间",
            "总金额",
            "产品列表",
            "实付金额",
            "代付金额",
            "收货人",
            "收货电话",
            "收货地址",
            "物流名称",
            "物流单号",
            "物流状态",
            "微信号",
            "销售员",
            "粉丝类型",
            "本月粉丝",
            "付款方式",
            "备注",
        ];
        foreach ($allList as $k=>$v){
            $cellData[$k+1][]=date("Y-m-d H:i",$v->add_time);
            $cellData[$k+1][]=$v->all_amount;
            $s="";
            foreach($v->goods as $gk=>$gv){
                $s.=$gv->goods_name.$gv->goods_num.$gv->unit."+";
            }
            $ns=rtrim($s, "+");
            $cellData[$k+1][]=$ns;
            $cellData[$k+1][]=$v->paid_amount;
            $cellData[$k+1][]=$v->collected_amount ;
            $cellData[$k+1][]=$v->receiver ;
            $cellData[$k+1][]=" ".$v->receiver_tel ." ";
            $cellData[$k+1][]=$v->express->country_name.",".$v->express->city_name.",".$v->express->region_name.",".$v->express->receiver_addr ;
            $cellData[$k+1][]=$v->express_type ;
            $cellData[$k+1][]=" ".$v->shipping_code." ";
            $status="";
            if( $v->express->shipping_status==0){
                $status="未发货";
            }else if( $v->express->shipping_status==1){
                $status="已发货";
            }else if( $v->express->shipping_status==2){
                $status="拒签";
            }else if( $v->express->shipping_status==3){
                $status="已签";
            }
            $cellData[$k+1][]=$status;
            $cellData[$k+1][]=$v->wx_no;
            $cellData[$k+1][]=$v->sale_name;
            $cellData[$k+1][]=$v->add_fen_type;
            $cellData[$k+1][]=$v->add_fen_month?'本月':'非本月';
            $cellData[$k+1][]=$v->pt_name==1?'全款':'到付';
            $cellData[$k+1][]=$v->remark;
        }

        outExcel($cellData, "订单" . date("Y-m-d H:i"));
    }

}
